#define _CRT_SECURE_NO_WARNINGS 1
#include"Dlist.h"


ListNode* ListInit()
{
	ListNode* phead = BuyListNode(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}


void ListDestory(ListNode* phead)
{
	assert(phead);
	ListNode* next = phead->next;
	while (next != phead)
	{
		next = next->next;
		free(next->prev);
	}
	free(phead);
	phead = NULL;
}


void ListPrint(ListNode* phead)
{
	assert(phead);
	ListNode* next = phead->next;
	while (next != phead)
	{
		printf("%d ", next->date);
		next = next->next;
	}
	printf("\n");
}



ListNode* BuyListNode(LTDateType x)
{
	ListNode* newlist = (ListNode*)malloc(sizeof(ListNode));
	if (newlist == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	else
	{
		newlist->date = x;
		newlist->prev = newlist->next = NULL;
		return newlist;
	}
}


void ListPushBack(ListNode* phead, LTDateType x)
{
	assert(phead);
	//ListNode* newlist = BuyListNode(x);
	//ListNode* tail = phead->prev;
	//phead->prev = newlist;
	//newlist->prev = tail;
	//tail->next = newlist;
	//newlist->next = phead;

	ListInsert(phead, phead, x);
}


void ListPushFront(ListNode* phead, LTDateType x)
{
	assert(phead);
	//ListNode* newlist = BuyListNode(x);
	//ListNode* first = phead->next;
	//phead->next = newlist;
	//newlist->next = first;
	//first->prev = newlist;
	//newlist->prev = phead;

	ListInsert(phead, phead->next, x);
}


void ListPopBack(ListNode* phead)
{
	//ListNode* tail = phead->prev->prev;
	//free(phead->prev);
	//tail->next = phead;
	//phead->prev = tail;

	ListErase(phead, phead->prev);
}


void ListPopFront(ListNode* phead)
{
	//ListNode* first = phead->next->next;
	//free(phead->next);
	//phead->next = first;
	//first->prev = phead;

	ListErase(phead, phead->next);
}


ListNode* FindListNode(ListNode* phead, LTDateType x)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->date == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	printf("Find fail\n");
	return NULL;
}


void ListInsert(ListNode* phead, ListNode* pop, LTDateType x)
{
	assert(phead && pop);
	ListNode* newlist = BuyListNode(x);
	ListNode* cur = pop->prev;
	cur->next = newlist;
	newlist->next = pop;
	newlist->prev = cur;
	pop->prev = newlist;
}


void ListErase(ListNode* phead, ListNode* pop)
{
	assert(phead && pop);
	pop->prev->next = pop->next;
	pop->next->prev = pop->prev;
	free(pop);
	pop = NULL;
}